package com.yang.mall.service.impl;

import com.yang.mall.dao.UserMapper;
import com.yang.mall.enums.RoleEnum;
import com.yang.mall.pojo.User;
import com.yang.mall.service.IUserService;
import com.yang.mall.vo.ResponseVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import java.nio.charset.StandardCharsets;

import static com.yang.mall.enums.ResponseEnum.*;

@Service
public class UserServiceImpl implements IUserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public ResponseVo<User> register(User user) {
        user.setRole(RoleEnum.CUSTOMER.getCode());
        // username不能重复
        int countByUsername = userMapper.countByUsername(user.getUsername());
        if(countByUsername > 0) {
            return ResponseVo.error(USERNAME_EXIST);
        }

        // email不能重复
        int countByEmail = userMapper.countByEmail(user.getEmail());
        if(countByEmail > 0) {
            return ResponseVo.error(EMAIL_EXIST);
        }

        // MD5摘要算法(Spring自带)
        user.setPassword(DigestUtils.md5DigestAsHex(user.getPassword().getBytes(StandardCharsets.UTF_8)));

        // 写入数据库
        int resultCount = userMapper.insertSelective(user);
        if(resultCount == 0){
            return ResponseVo.error(ERROR);
        }
        return ResponseVo.success();
    }

    @Override
    public ResponseVo<User> login(String username, String password) {
        User user = userMapper.selectByUsername(username);
        if (user == null){
            //返回账号或尼玛错误，一种安全措施
            return ResponseVo.error(USERNAME_OR_PASSWORD_ERROR);
        }
        if (!user.getPassword().equalsIgnoreCase(
                DigestUtils.md5DigestAsHex(password.getBytes(StandardCharsets.UTF_8)))) {
            //返回账号或尼玛错误，一种安全措施
            return ResponseVo.error(USERNAME_OR_PASSWORD_ERROR);
        }
        // 隐藏密码
        user.setPassword("");
        return ResponseVo.success(user);
    }
}
